package service

import (
	"errors"
	"fmt"
	"log"
	"ssr/common"
	"ssr/dto"
	"ssr/models"

	"gorm.io/gorm"
)

type WaterService struct {
	db *gorm.DB
}

func NewWaterService() *WaterService {
	return &WaterService{
		db: common.GetDB(),
	}
}

func (s *WaterService) CreateDict(dict dto.DictCreateDTO) (string, error) {
	var dictModel models.WaterDict
	if dict.DictId != "" {
		if err := s.db.Model(&models.WaterDict{}).Where("id = ?", dict.DictId).Updates(&models.WaterDict{
			Phone: dict.Phone,
			Desc:  dict.Desc,
			Stock: dict.Stock,
			Price: dict.Price,
			Value: dict.Value,
		}).Error; err != nil {
			return "更新失败", err
		}
		return "更新成功", nil
	}
	// 查询手机号是否存在
	if err := s.db.Where("phone = ?", dict.Phone).First(&dictModel).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return "查询失败", err
	}
	if dictModel.Phone == dict.Phone {
		return "手机号已存在", errors.New("手机号已存在")
	}

	if err := s.db.Create(&models.WaterDict{
		Phone: dict.Phone,
		Desc:  dict.Desc,
		Stock: dict.Stock,
		Price: dict.Price,
		Value: dict.Value,
	}).Error; err != nil {
		return "创建失败", err
	}
	return "创建成功", nil
}
func (s *WaterService) DeleteDict(dictId string) (string, error) {
	if err := s.db.Delete(&models.WaterDict{}, "id = ?", dictId).Error; err != nil {
		return "删除失败", err
	}
	return "删除成功", nil
}

func (s *WaterService) GetDictList(params dto.QueryDictListDTO) (*common.Pagination[models.WaterDict], error) {
	var dictList []models.WaterDict
	var total int64
	searchKey := fmt.Sprintf("%%%s%%", params.Keyword)
	querySql := "phone LIKE ? OR " + "`desc`" + " LIKE ? OR " + "`value`" + " LIKE ?"
	if err := s.db.Model(&models.WaterDict{}).Where(querySql, searchKey, searchKey, searchKey).
		Count(&total).Error; err != nil {
		return nil, err
	}
	if err := s.db.Model(&models.WaterDict{}).Where(querySql, searchKey, searchKey, searchKey).
		Limit(params.Limit).
		Offset((params.Page - 1) * params.Limit).
		Find(&dictList).Error; err != nil {
		return nil, err
	}
	log.Println(dictList, "dictList")
	result := common.NewPagination(params.Page, params.Limit, total, dictList)
	return result, nil
}
func (s *WaterService) Recharge(dictId string, amount int) (string, error) {
	var dict models.WaterDict
	if err := s.db.Where("id = ?", dictId).First(&dict).Error; err != nil {
		return "查询失败", err
	}
	dict.Stock += int(amount)
	if err := s.db.Save(&dict).Error; err != nil {
		return "充值失败", err
	}
	return "添加成功", nil
}

func (s *WaterService) GetWaterOrderList(params dto.QueryOrderListDTO) (*common.Pagination[models.WaterOrder], error) {
	var orderList []models.WaterOrder
	var total int64
	searchKey := fmt.Sprintf("%%%s%%", params.Keyword)
	querySql := "(" + "phone LIKE ? OR " + "`desc`" + " LIKE ? OR " + "`address`" + " LIKE ? OR" + "`link_man`" + " LIKE ?" + ")"
	querySql = querySql + " AND status != -1"
	if err := s.db.Model(&models.WaterOrder{}).
		Where(querySql, searchKey, searchKey, searchKey, searchKey).
		Count(&total).Error; err != nil {
		return nil, err
	}
	limit := params.Limit
	offset := (params.Page - 1) * limit
	if err := s.db.Model(&models.WaterOrder{}).
		Where(querySql, searchKey, searchKey, searchKey, searchKey).
		Limit(limit).
		Offset(offset).
		Order("created_at desc").
		Find(&orderList).Error; err != nil {
		return nil, err
	}
	result := common.NewPagination(params.Page, params.Limit, total, orderList)
	return result, nil
}

func (s *WaterService) CreateOrder(order dto.CreateOrderDTO) (string, error) {
	tx := s.db.Begin()
	var dict models.WaterDict
	if err := tx.Where("phone = ?", order.Phone).First(&dict).Error; err != nil {
		tx.Rollback()
		return "查询失败", errors.New("手机号不存在")
	}
	if dict.ID == "" {
		return "手机号不存在", errors.New("手机号不存在")
	}
	if dict.Stock < order.Quantity {
		return "库存不足", errors.New("库存不足")
	}
	if err := tx.Create(&models.WaterOrder{
		Phone:    order.Phone,
		Quantity: order.Quantity,
		Price:    dict.Price,
		Linkman:  order.Linkman,
		Address:  order.Address,
		DictId:   dict.ID,
		Desc:     order.Desc,
		Status:   0,
	}).Error; err != nil {
		tx.Rollback()
		return "创建失败", err
	}
	if err := tx.Model(&models.WaterDict{}).Where("id = ?", dict.ID).Update("stock", dict.Stock-order.Quantity).Error; err != nil {
		tx.Rollback()
		return "更新库存失败", err
	}
	tx.Commit()
	return "创建成功", nil
}

func (s *WaterService) ConfirmOrder(orderId string, status int) (string, error) {
	tx := s.db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Model(&models.WaterOrder{}).
		Where("id = ?", orderId).
		Update("status", status).Error; err != nil {
		tx.Rollback()
		return "更新失败", err
	}
	tx.Commit()
	return "更新成功", nil
}
func (s *WaterService) CancelOrder(orderId string) (string, error) {
	var order models.WaterOrder
	tx := s.db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Model(&models.WaterOrder{}).
		Where("id = ?", orderId).
		First(&order).Error; err != nil {
		tx.Rollback()
		return "查询失败", err
	}
	if order.Status != 0 {
		return "订单已在流程中，无法取消", nil
	}
	// 返还库存
	var dict models.WaterDict
	if err := tx.Model(&models.WaterDict{}).
		Where("id = ?", order.DictId).
		First(&dict).Error; err != nil {
		tx.Rollback()
		return "查询失败", err
	}
	dict.Stock += order.Quantity
	if err := tx.Save(&dict).Error; err != nil {
		tx.Rollback()
		return "更新库存失败", err
	}

	if err := tx.Model(&models.WaterOrder{}).
		Where("id = ?", orderId).
		Update("status", -2).
		Error; err != nil {
		tx.Rollback()
		return "更新失败", err
	}
	tx.Commit()
	return "取消成功", nil
}

func (s *WaterService) DeleteOrder(orderId string) (string, error) {
	var order models.WaterOrder
	tx := s.db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	if err := tx.Where("id = ?", orderId).First(&order).Error; err != nil {
		tx.Rollback()
		return "查询失败", err
	}
	if order.Status == 1 {
		return "订单已在流程中，无法删除", nil
	}
	// 如果是未完成订单，返还库存 0还未接单 -2 已取消
	if order.Status == 0 {
		// 返还库存
		var dict models.WaterDict
		if err := tx.Where("id = ?", order.DictId).First(&dict).Error; err != nil {
			tx.Rollback()
			return "查询失败", err
		}
		dict.Stock += order.Quantity
		if err := s.db.Save(&dict).Error; err != nil {
			tx.Rollback()
			return "更新库存失败", err
		}
	}
	// 已完成的订单删除时做备份
	if order.Status == 2 {
		if err := s.db.Model(&models.WaterOrder{}).Where("id = ?", orderId).Updates(&models.WaterOrder{
			Status: -1,
		}).Error; err != nil {
			tx.Rollback()
			return "删除失败", err
		}
		tx.Commit()
		return "删除成功", nil
	}
	if err := tx.Delete(&models.WaterOrder{}, "id = ?", orderId).Error; err != nil {
		tx.Rollback()
		return "删除失败", err
	}
	tx.Commit()
	return "删除成功", nil
}

func (s *WaterService) GetOrderDetail(orderId string) (map[string]interface{}, error) {
	var order models.WaterOrder
	if err := s.db.Where("id = ?", orderId).First(&order).Error; err != nil {
		return nil, err
	}
	var dict models.WaterDict
	if err := s.db.Where("id = ?", order.DictId).First(&dict).Error; err != nil {
		return nil, err
	}
	return map[string]interface{}{
		"order": order,
		"dict":  dict,
	}, nil
}
